﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace Saxxon.LibDoomSharp
{
    /// <summary>
    /// A wrapper for IO.BinaryWriter that contains support for fixed length string fields and code page 437.
    /// </summary>
    public class DataWriter : BinaryWriter
    {
        /// <summary>
        /// Most common DOS code page (and incidentally the one used by Doom)
        /// </summary>
        const int DOS_CODEPAGE = 437;

        /// <summary>
        /// Instantiate a DataWriter for the specified stream.
        /// </summary>
        public DataWriter(Stream stream)
            : base(stream, Encoding.GetEncoding(DOS_CODEPAGE))
        {
        }

        /// <summary>
        /// Write a Byte to the stream, regardless of the input value's type.
        /// </summary>
        public void WriteInt8(int value)
        {
            Write(Convert.ToByte(value));
        }

        /// <summary>
        /// Write an Int16 to the stream, regardless of the input value's type.
        /// </summary>
        public void WriteInt16(int value)
        {
            Write(Convert.ToInt16(value));
        }

        /// <summary>
        /// Write an Int32 to the stream, regardless of the input value's type.
        /// </summary>
        public void WriteInt32(int value)
        {
            Write(Convert.ToInt32(value));
        }

        /// <summary>
        /// Write a string to the stream in a fixed length field.
        /// </summary>
        public void WriteString(string s, int bytes, char fill = '\0')
        {
            string value = s;

            // truncate string if necessary
            if (value.Length > bytes)
            {
                value = value.Substring(0, bytes);
            }

            // pad string if necessary
            StringBuilder builder = new StringBuilder(value);
            while (builder.Length < bytes)
            {
                builder.Append(fill);
            }

            // format output
            char[] output = new char[bytes];
            builder.CopyTo(0, output, 0, bytes);

            Write(output);
        }

        /// <summary>
        /// Write a UInt16 to the stream, regardless of the input value's type.
        /// </summary>
        public void WriteUInt16(uint value)
        {
            Write(Convert.ToUInt16(value));
        }

        /// <summary>
        /// Write a UInt32 to the stream, regardless of the input value's type.
        /// </summary>
        public void WriteUInt32(uint value)
        {
            Write(Convert.ToUInt32(value));
        }
    }
}
